﻿using Kingdee.BOS;
using Kingdee.BOS.Contracts;
using Kingdee.BOS.Contracts.Report;
using Kingdee.BOS.Core.Enums;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.Core.Report;
using Kingdee.BOS.Core.SqlBuilder;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Util;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RK.ReportPlugin.XHX
{
    [Description("利润明细表"), HotUpdate]
    public class AccountingDetailRpt : SysReportBaseService
    {
        //初始化
        public override void Initialize()
        {
            base.Initialize();
            // 简单账表类型：普通、树形、分页
            this.ReportProperty.ReportType = ReportType.REPORTTYPE_NORMAL;
            this.IsCreateTempTableByPlugin = false;
            //是否分组汇总
            this.ReportProperty.IsGroupSummary = false;
        }
        ///构建from where语句
        protected override string BuilderFromWhereSQL(IRptParams filter)
        {
            DynamicObject customFilter = filter.FilterParameter.CustomFilter;
            StringBuilder strwhere = new StringBuilder();
            strwhere.AppendLine(@" from 
                                (
	                                select t0.FID, t1.FENTRYID,t0.FPURCHASEORGID,t1UO_L.FNAME FOrgname,SUPP_L.FNAME FSuppName
	                                ,t0.FBILLNO
	                                ,t0.FDate
	                                ,t0.FDOCUMENTSTATUS
	                                ,t2.FLOCALCURRID
	                                ,t1.FMATERIALID
	                                ,t1M_L.FNAME as FMaterialName
	                                ,t1.FQTY
	                                ,t1U_L.FNAME as FUnitName
	                                ,t1f.FTAXPRICE
	                                ,t1f.FALLAMOUNT
	                                from T_PUR_POORDER t0
	                                inner join T_PUR_POORDERFIN t2 on (t0.FID = t2.FID)
	                                left join T_BD_CURRENCY t20 on (t2.FLOCALCURRID = t20.FCURRENCYID)
	                                inner join T_PUR_POORDERENTRY t1 on (t0.FID = t1.FID)
	                                left join T_BD_MATERIAL_L t1M_L on (t1.FMATERIALID = t1m_l.FMATERIALID and t1M_L.FLOCALEID = 2052)
	                                inner join T_PUR_POORDERENTRY_F t1F on (t1.FENTRYID = t1f.FENTRYID)
	                                left join T_BD_UNIT t1U on (t1f.FPRICEUNITID = t1u.FUNITID)
	                                left join T_BD_UNIT_L t1U_L on (t1U.FUNITID = t1U_L.FUNITID and t1U_L.FLOCALEID = 2052) 
	                                left join T_ORG_ORGANIZATIONS_L t1UO_L on (t0.FPURCHASEORGID = t1UO_L.FORGID and t1UO_L.FLOCALEID = 2052)
	                                left join T_BD_SUPPLIER_L SUPP_L on (t0.FSUPPLIERID = SUPP_L.FSUPPLIERID and SUPP_L.FLOCALEID = 2052) 
                                ) t1  Where 1=1 ");

            //组织
            string org = string.IsNullOrWhiteSpace(customFilter["F_PAEZ_OrgId"].ToString())
                ? " " : string.Format(" AND FPURCHASEORGID IN ({0}) ", Convert.ToString(customFilter["F_PAEZ_OrgId"]));
            strwhere.AppendLine(org);


            //日期
            string startValue = (customFilter["FOrderStartDate"] == null) ? string.Empty : Convert.ToDateTime(customFilter["FOrderStartDate"]).ToString("yyyy-MM-dd");
            string endValue = (customFilter["FOrderEndDate"] == null) ? string.Empty : Convert.ToDateTime(customFilter["FOrderEndDate"]).ToString("yyyy-MM-dd");
            strwhere.AppendLine(string.Format(" AND FDate>='{0}' and FDate<='{1}' ", startValue, endValue));

            //物料
            string baseDataNameValue = this.GetBaseDataNameValue(customFilter["F_PAEZ_WLID"] as DynamicObjectCollection);
            string MaterailName = string.IsNullOrWhiteSpace(baseDataNameValue)
                ? " " : string.Format(" AND FMaterialName IN ({0}) ", baseDataNameValue);
            strwhere.AppendLine(MaterailName);
            //单据编号
            string BillNo = (Convert.ToString(customFilter["F_PoOrderBillNo"]) == "") ? " " : "  AND FBILLNO='" + customFilter["F_PoOrderBillNo"].ToString() + "' ";
            strwhere.AppendLine(BillNo);

            //供应商
            string baseSuppName = this.GetBaseDataNameValue(customFilter["F_PAEZ_SuppId"] as DynamicObjectCollection);
            string SuppName = string.IsNullOrWhiteSpace(baseSuppName)
                ? " " : string.Format(" AND FSuppName IN ({0}) ", baseSuppName);
            strwhere.AppendLine(SuppName);



            string text2 = string.IsNullOrWhiteSpace(filter.FilterParameter.FilterString) ? " " : " AND " + filter.FilterParameter.FilterString.Replace("{ts", "").Replace("}", "");
            strwhere.AppendLine(text2);



            return strwhere.ToString();
        }
        //构建单据select 和字段
        protected override string BuilderSelectFieldSQL(IRptParams filter)
        {
            string sqlstr = @"select FID, FENTRYID,FPURCHASEORGID,FOrgname,FSuppName,FBILLNO,FDate,FDOCUMENTSTATUS
                               ,FLOCALCURRID,FMATERIALID,FMaterialName,FQTY,FUnitName,FTAXPRICE,FALLAMOUNT";
            return sqlstr;
        }
        //构建order by语句
        protected override string BuilderTempTableOrderBySQL(IRptParams filter)
        {
            string OrderBy = "";
            string datasort = Convert.ToString(filter.FilterParameter.SortString);//排序
            if (datasort != "")
            {
                OrderBy = datasort;
            }
            else
            {
                OrderBy = " FID ";
            }
            return OrderBy;
        }
        /// 设置汇总列信息
        public override List<SummaryField> GetSummaryColumnInfo(IRptParams filter)
        {
            var result = base.GetSummaryColumnInfo(filter);
            result.Add(new SummaryField("FQty", BOSEnums.Enu_SummaryType.SUM));
            result.Add(new SummaryField("FALLAMOUNT", BOSEnums.Enu_SummaryType.SUM));
            return result;
        }
        //创建临时报表
        public override void BuilderReportSqlAndTempTable(IRptParams filter, string tableName)
        {
            base.BuilderReportSqlAndTempTable(filter, tableName);
        }
        //设置单据列
        public override ReportHeader GetReportHeaders(IRptParams filter)
        {
            ReportHeader header = new ReportHeader();
            ReportHeader headerch = new ReportHeader();
            // 编号
            header.AddChild("FOrgname", new LocaleValue("标题一&业务组织", this.Context.UserLocale.LCID), SqlStorageType.Sqlvarchar);
            header.AddChild("FSuppName", new LocaleValue("标题一&客户", this.Context.UserLocale.LCID), SqlStorageType.Sqlvarchar);
            header.AddChild("FDocumentStatus", new LocaleValue("标题一&状态", this.Context.UserLocale.LCID), SqlStorageType.Sqlvarchar);
            header.AddChild("FDate", new LocaleValue("标题一&日期", this.Context.UserLocale.LCID), SqlStorageType.SqlDatetime);
            header.AddChild("FBillNo", new LocaleValue("标题一&单据编号", this.Context.UserLocale.LCID), SqlStorageType.Sqlvarchar);
            header.AddChild("FMaterialName", new LocaleValue("标题二&物料", this.Context.UserLocale.LCID), SqlStorageType.Sqlvarchar);
            header.AddChild("FQty", new LocaleValue("标题二&数量", this.Context.UserLocale.LCID), SqlStorageType.SqlDecimal);
            header.AddChild("FUnitName", new LocaleValue("标题二&单位", this.Context.UserLocale.LCID), SqlStorageType.Sqlvarchar);
            header.AddChild("FTAXPRICE", new LocaleValue("标题二&含税价", this.Context.UserLocale.LCID), SqlStorageType.SqlDecimal);
            header.AddChild("FALLAMOUNT", new LocaleValue("标题二&价税合计", this.Context.UserLocale.LCID), SqlStorageType.SqlDecimal);


            return header;
        }
        //获取过滤条件信息(构造单据信息)
        public override ReportTitles GetReportTitles(IRptParams filter)
        {
            ReportTitles reportTitles = new ReportTitles();
            DynamicObject customFilter = filter.FilterParameter.CustomFilter;
            if (customFilter != null)
            {
                string multiOrgnNameValues = this.GetMultiOrgnNameValues(customFilter["F_qwer_OrgId"].ToString());
                string startYear = (customFilter["F_Year_Date"] == null) ? string.Empty : Convert.ToDateTime(customFilter["F_Year_Date"]).ToString();
                string endYear = (customFilter["F_EndYear_Date"] == null) ? string.Empty : Convert.ToDateTime(customFilter["F_EndYear_Date"]).ToString();
                string startMonth = (customFilter["F_Month_Date"] == null) ? string.Empty : Convert.ToDateTime(customFilter["F_Month_Date"]).ToString();
                string endMonth = (customFilter["F_EndMonth_Date"] == null) ? string.Empty : Convert.ToDateTime(customFilter["F_EndMonth_Date"]).ToString();
                string F_IsPOSTED = (customFilter["F_IsPOSTED"] == null) ? string.Empty : Convert.ToDateTime(customFilter["F_IsPOSTED"]).ToString();
                string F_IsBore = (customFilter["F_IsBore"] == null) ? string.Empty : Convert.ToDateTime(customFilter["F_IsBore"]).ToString();
                string baseDataNameValue = this.GetBaseDataNameValue(customFilter["F_PAEZ_WLID"] as DynamicObjectCollection);
                string baseDataNameValue3 = this.GetBaseDataNameValue(customFilter["F_PAEZ_SuppId"] as DynamicObjectCollection);
                reportTitles.AddTitle("F_PAEZ_Org", multiOrgnNameValues);
                reportTitles.AddTitle("F_Year_Date", startYear);
                reportTitles.AddTitle("F_EndYear_Date", endYear);
                reportTitles.AddTitle("F_Month_Date", startMonth);
                reportTitles.AddTitle("F_EndMonth_Date", endMonth);
                reportTitles.AddTitle("F_IsPOSTED", F_IsPOSTED);
                reportTitles.AddTitle("F_IsBore", F_IsBore);

            }
            return reportTitles;
        }

        private string GetBaseDataNameValue(DynamicObjectCollection dyobj)
        {
            string name = "";
            foreach (DynamicObject dynbj in dyobj)
            {
                if (dynbj != null || !dynbj.DynamicObjectType.Properties.Contains("Name"))
                {
                    DynamicObject dynbj2 = (DynamicObject)dynbj[2];
                    name = name + ",'" + dynbj2["Name"].ToString() + "'";
                }
            }
            if (name.Length > 0)
            {
                name = name.Substring(1, name.Length - 1);
            }
            return name;
        }

        private string GetMultiOrgnNameValues(string orgIdStrings)
        {
            List<string> list = new List<string>();
            string result = string.Empty;
            if (orgIdStrings.Trim().Length > 0)
            {
                IQueryService service = ServiceFactory.GetService<IQueryService>(base.Context);
                QueryBuilderParemeter para = new QueryBuilderParemeter
                {
                    FormId = "ORG_Organizations",
                    SelectItems = SelectorItemInfo.CreateItems("FNAME"),
                    FilterClauseWihtKey = string.Format(" FORGID IN ({0}) AND FLOCALEID={1}", orgIdStrings, base.Context.UserLocale.LCID)
                };
                DynamicObjectCollection dynamicObjectCollection = service.GetDynamicObjectCollection(base.Context, para, null);
                foreach (DynamicObject current in dynamicObjectCollection)
                {
                    list.Add(current["FNAME"].ToString());
                }
                if (list.Count > 0)
                {
                    result = string.Join(",", list.ToArray());
                }
            }
            return result;
        }
    }
}
